import { Commit, ActionTree, MutationTree } from 'vuex';
import * as types from '@/store/mutation-types';
import { AxiosResponse } from 'axios';
import graph from '@/graph';
import { Alarm, AlarmParams } from '@/types/alarm';
import {Option} from "@/types/global";

export interface State {
  services: Option[];
  instances: Option[];
  alarmService: Alarm[];
  total: number;
}

const initState: State = {
  services: [],
  instances: [],
  alarmService: [],
  total: 0,
};

// getters
const getters = {};

// mutations
const mutations: MutationTree<State> = {
  [types.SET_SERVICES](state: State, data: Option[]): void {
      state.services = [{label: 'ALL', key: ''}].concat(data);
  },
  [types.SET_INSTANCES](state: State, data: Option[]): void {
      state.instances = data;
  },
  [types.SET_ALARM](state: State, data: Alarm[]): void {
    state.alarmService = data;
  },
  [types.SET_ALARM_TOTAL](state: State, total: number): void {
    state.total = total;
  },
  [types.CLEAR_ALARM](state: State): void {
    state.alarmService = [];
  },
};

// actions
const actions: ActionTree<State, any> = {
  GET_ALARM(context: { commit: Commit; state: State}, params: AlarmParams): Promise<void> {
    return graph
      .query('queryAlarms')
      .params(params)
      .then((res: AxiosResponse<any>) => {
        if (res.data.data) {
          context.commit(types.SET_ALARM, res.data.data.list);
          context.commit(types.SET_ALARM_TOTAL, res.data.data.total);
        }
      });
  },
  GET_SERVICES(context: { commit: Commit }, params: any): Promise<void> {
      return graph
          .query('queryServices')
          .params(params)
          .then((res: AxiosResponse) => {
              context.commit(types.SET_SERVICES, res.data.data);
          });
  },
  GET_INSTANCES(context: { commit: Commit }, params: any): Promise<void> {
      return graph
          .query('queryInstances')
          .params(params)
          .then((res: AxiosResponse) => {
              context.commit(types.SET_INSTANCES, res.data.data);
          });
  },
  CLEAR_ALARM(context: { commit: Commit; state: State }): void {
    context.commit(types.CLEAR_ALARM);
  },
};

export default {
  namespaced: true,
  state: initState,
  getters,
  actions,
  mutations,
};
